package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * description XMLConfigBuilder
 * author wy
 * date 2021-04-06 23:20
 **/
public class XMLConfigBuilder
{
    private Configuration configuration;

    public XMLConfigBuilder() {
        configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException
    {
        //解析sqlMapConfig.xml
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list)
        {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        //解析获取数据源dataSource
        ComboPooledDataSource pooledDataSource = new ComboPooledDataSource();
        pooledDataSource.setDriverClass(properties.getProperty("dataSource"));
        pooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        pooledDataSource.setUser(properties.getProperty("username"));
        pooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(pooledDataSource);

        //解析并获取到mapper文件
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList)
        {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }


        return configuration;
    }
}
